﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using NNS.Enumeration;
using NNS.Framework;
using NNS.UI;
using QLTB.BusinessLayer;
using QLTB.Common;
using QLTB.NhaCungCap.Entity;

namespace QLTB.UI
{
    [System.ComponentModel.ToolboxItem(false)]
    public partial class ucNHACUNGCAP : MyUIBase
    {
        private readonly DataView dv;

        public ucNHACUNGCAP()
        {
            InitializeComponent();

            Nap();
            TBL_quyenBL.IgnoreError = true;
            if (!TBL_quyenBL.isTaomoi(EnumComponent.iProvider))
            {
                gbList.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            }
            TBL_quyenBL.IgnoreError = false;

            dsNHACUNGCAP.TBL_NHACUNGCAP.TBL_NHACUNGCAPRowChanging += TBL_NHACUNGCAP_TBL_NHACUNGCAPRowChanging;
            dsNHACUNGCAP.TBL_NHACUNGCAP.TBL_NHACUNGCAPRowChanged -= TBL_NHACUNGCAP_TBL_NHACUNGCAPRowChanged;
            dsNHACUNGCAP.TBL_NHACUNGCAP.TBL_NHACUNGCAPRowDeleted += TBL_NHACUNGCAP_TBL_NHACUNGCAPRowDeleted;

            gcList.DataSource = dv = dsNHACUNGCAP.TBL_NHACUNGCAP.DefaultView;
        }

        public bool isFilter
        {
            get { return gbList.OptionsView.ShowAutoFilterRow; }

            set { gbList.OptionsView.ShowAutoFilterRow = value; }
        }

        private void TBL_NHACUNGCAP_TBL_NHACUNGCAPRowDeleted(object sender, dsNHACUNGCAP.TBL_NHACUNGCAPRowChangeEvent e)
        {
            OnSaveChanging(new SaveChangingEventArgs(e.Row.Table.Rows.Count%100));
        }

        private void TBL_NHACUNGCAP_TBL_NHACUNGCAPRowChanging(object sender, dsNHACUNGCAP.TBL_NHACUNGCAPRowChangeEvent e)
        {
            //throw new NotImplementedException();
            if (Mode == EditMode.Load)
            {
                return;
            }
            if (Mode == EditMode.Update) return;
            if (e.Action == DataRowAction.Change)
            {
                if (!TBL_quyenBL.isThaydoi(EnumComponent.iProvider))
                {
                    Nap();
                    NotSave = false;
                    return;
                }
            }
        }

        public void Nap()
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            var speedtimer = new Stopwatch();
            speedtimer.Start();
            gcList.Enabled = false;
            Mode = EditMode.Load;
            //SqlHelper.Helper.Fill(CommandType.Text,
            //                                        "SELECT  MaNCC, TenNCC, DiaChi, DT, BaoHanh FROM TBL_NHACUNGCAP ORDER BY TenNCC",
            //                                        dsNHACUNGCAP.TBL_NHACUNGCAP);
            try
            {
                tBL_NHACUNGCAPTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                //tBL_NHACUNGCAPTableAdapter.Adapter.FillLoadOption = LoadOption.PreserveChanges;
                tBL_NHACUNGCAPTableAdapter.Fill(dsNHACUNGCAP.TBL_NHACUNGCAP);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Quản lý nhà cung cấp");
            }


            Mode = EditMode.None;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            gcList.Enabled = true;
            speedtimer.Stop();

            Cursor.Current = current;
        }

        private void TBL_NHACUNGCAP_TBL_NHACUNGCAPRowChanged(object sender, dsNHACUNGCAP.TBL_NHACUNGCAPRowChangeEvent e)
        {
            OnSaveChanging(new SaveChangingEventArgs(e.Row.Table.Rows.Count%100)
                               {Status = e.Row.Table.Rows.Count.ToString()});
        }

        public override void Save()
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            Mode = EditMode.Update;
            dsNHACUNGCAP.TBL_NHACUNGCAPDataTable dt = dsNHACUNGCAP.TBL_NHACUNGCAP;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                if (dr.RowState != DataRowState.Deleted)
                {
                    if (dr[dt.TenNCCColumn] == DBNull.Value)
                    {
                        ShowWarning("Không được bỏ trống!", "Quản lý nhà cung cấp");
                        Mode = EditMode.None;
                        speedtimer.Stop();
                        gcList.Enabled = true;
                        OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
                        Cursor.Current = current;
                        return;
                    }
                }
            }

            try
            {
                tBL_NHACUNGCAPTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_NHACUNGCAPTableAdapter.Adapter.RowUpdated += Adapter_RowUpdated;
                tBL_NHACUNGCAPTableAdapter.Update(dsNHACUNGCAP.TBL_NHACUNGCAP);
                NotSave = false;
                dsNHACUNGCAP.AcceptChanges();
            }
            catch (Exception ex)
            {
                ShowWarning(ex.Message, "Quản lý nhà cung cấp");
            }

            Mode = EditMode.None;
            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        private void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            OnSaveChanging(new SaveChangingEventArgs(e.RowCount, dsNHACUNGCAP.TBL_NHACUNGCAP.Count));
            //throw new NotImplementedException();
        }

        private void gbList_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            ValidateData();
        }

        private void ValidateData()
        {
            //for (int i = 0; i < gbList.RowCount; i++)
            //{

            //}
        }

        private void gbList_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            NotSave = true;
            OnSaveChanged(new SaveChangedEventArgs {NotSave = true});
        }

        private void ucNHACUNGCAP_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                Deleted();
            }
        }

        public void Deleted()
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iProvider)) return;

            if (ShowQuestion("Bạn thật sự muốn xóa không?", "Quản lý nhà cung cấp") == DialogResult.No) return;

            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            gbList.DeleteSelectedRows();
            NotSave = true;

            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        public void SelectAll()
        {
            gbList.SelectAll();
        }

        public void Copy()
        {
            gbList.CopyToClipboard();
        }

        public void ClearContext()
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iProvider)) return;

            if (ShowQuestion("Bạn thật sự muốn xóa không?", "Quản lý nhà cung cấp") == DialogResult.No) return;


            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            gbList.SelectAll();
            gbList.DeleteSelectedRows();
            NotSave = true;

            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        public void Cancel()
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            dsNHACUNGCAP.RejectChanges();
            NotSave = false;

            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        private void gbList_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            int rowIndex = e.RowHandle;
            if (rowIndex >= 0)
            {
                rowIndex++;
                e.Info.DisplayText = rowIndex.ToString();
            }
        }

        private void gbList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                Deleted();
            }
        }

        private void txtTimnhanh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Filter();
            }
        }

        private void txtTimnhanh_EditValueChanged(object sender, EventArgs e)
        {
            if (!chxAuto.Checked) return;
            Filter();
        }

        private void Filter()
        {
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();
            dv.RowFilter = "TenNCC like '%" + txtTimnhanh.Text + "%' OR DiaChi like '%" + txtTimnhanh.Text +
                           "%' OR DT LIKE '%" + txtTimnhanh.Text + "%'";
            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
        }

        private void txtTimnhanh_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            txtTimnhanh.Text = "";
            dv.RowFilter = "";
        }
    }
}